package com.ruoyi.web.controller.websocket;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.ruoyi.RuoYiApplication;
import com.ruoyi.system.domain.Message;
import com.ruoyi.system.service.MessageService;
import com.ruoyi.system.service.impl.MessageServiceImpl;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

//@ServerEndpoint("/websocket/{user}")
@ServerEndpoint(value = "/api/websocket/{user}/{otherUser}")
@Component
@Service
public class MyWebSocketServer {


	//静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
	private static int onlineCount = 0;
	//concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
	private static CopyOnWriteArraySet<MyWebSocketServer> webSocketSet = new CopyOnWriteArraySet<MyWebSocketServer>();
    private Map<String,Session> sessionMap = new HashMap<String,Session>();
	//与某个客户端的连接会话，需要通过它来给客户端发送数据
	private String user;
	private String otherUser;
	private MessageService messageService = RuoYiApplication.getBean(MessageServiceImpl.class);
	/**
	 * 连接建立成功调用的方法
	 */
	@OnOpen
	public void onOpen(@PathParam("user") String user, @PathParam("otherUser") String otherUser, Session session) {
		System.out.println(user+"   连接成功     "+otherUser);
		this.sessionMap.put(user,session);
		this.user = user;
		this.otherUser = otherUser;
		webSocketSet.add(this); // 加入set中
		System.out.println(user+"   有新连接加入！ 当前在线人数" + onlineCount);
	}

	/**
	 * 连接关闭调用的方法
	 */
	@OnClose
	public void onClose() {
		webSocketSet.remove(this); // 从set中删除
		subOnlineCount(); // 在线数减1
		System.out.println("连接关闭");
		System.out.println("有连接关闭！ 当前在线人数" + onlineCount);
	}

	/**
	 * 收到客户端消息后调用的方法
	 *
	 * @param message 客户端发送过来的消息
	 */
	@OnMessage
	public void onMessage(String message) {
		System.out.println("来自" + user + "消息：" + message);
		System.out.println(user+"        "+otherUser);
		try {
			this.sessionMap.get(user).getBasicRemote().sendText(message);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Message messages = new Message();
		messages.setUser(Long.valueOf(user));
		messages.setOther(Long.valueOf(otherUser));
		messages.setMage(message);
			messageService.insertMessage(messages);
		if(this.sessionMap.get(otherUser)!=null){
			try {
				this.sessionMap.get(otherUser).getBasicRemote().sendText(message);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 *
	 * @param session
	 * @param error
	 */
	@OnError
	public void onError(Session session, Throwable error) {

		error.printStackTrace();
	}

	public static synchronized int getOnlineCount() {
		return onlineCount;
	}

	public static synchronized void addOnlineCount() {
		MyWebSocketServer.onlineCount++;
	}

	public static synchronized void subOnlineCount() {
		MyWebSocketServer.onlineCount--;
	}
}
